﻿Imports ADOConnection
Imports CrystalDecisions.CrystalReports.Engine

Public Class frmPhieuNX

#Region "Paramaters"
    Public fViewPhieuNX As frmViewPhieuNX = Nothing
    Public objPhieu As CPhieuNX
    Public enumNX As enumDOITUONG 'De xac dinh phieu nhap, phieu xuat

    'Chi dung cho cmbLK(cmbLoaiMH) 
    'de kiem tra neu chon Loai Kho( Loai Thuoc) khac se mat du lieu mat hang
    Private objLK As CDoiTuong
    Private objLoaiMH As CLoaiThuoc

    'Cac bien dung de truy xuat du lieu in DatagridView
    Private sdaSLNX As IDbDataAdapter
    'Private bsSLNX As New BindingSource
    Private dsDataSet As DataSet
    Private RowCount As Integer = 0 'De xu ly SoKH khi them mathang moi 

    'Bien dung de tinh toan lai slton tai thoi diem cua phieu xuat can chinh sua
    Public sltonkh As Double = 0
    Public sltonth As Double = 0

    Public Enum enumLabelNotify
        None = -1
        DOITUONG = 0
        MaColumn = 2
        HSDColumn = 3
        SLKHColumn = 4
        SLTHColumn = 5
    End Enum
#End Region

#Region "Events"

#Region "General"
    Private Sub frmPhieuNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Lay danh sach Loai Kho
        Dim arys As ArrayList = CDoiTuongs.GetDoiTuongList(enumDOITUONG.LOAIKHO)
        cmbLK.DisplayMember = "Ten"
        cmbLK.ValueMember = "KH"
        cmbLK.DataSource = arys

        'Lay danh sach Loai Thuoc
        arys = CLoaiThuocs.GetLoaiThuocListByMaCha(CLoaiThuocs.GetLoaiThuocByTen("Kho 706").MaLoaiThuoc)
        cmbLoaiMH.DisplayMember = "TenLoaiThuoc"
        cmbLoaiMH.ValueMember = "MaLoaiThuoc"
        cmbLoaiMH.DataSource = arys

        'Lay danh sach HTTT
        arys = CDoiTuongs.GetDoiTuongList(enumDOITUONG.THANHTOAN)
        cmbHTTT.DisplayMember = "Ten"
        cmbHTTT.ValueMember = "KH"
        cmbHTTT.DataSource = arys

        If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
            chkTCXacNhan.Visible = True
            btnXoa.Visible = False
            btnCapnhatNew.Visible = False
            btnInPhieu.Visible = False
        Else
            chkTCXacNhan.Visible = False
        End If
        lblNotify.Text = ""
        Init()
    End Sub

    Private Sub cmbLK_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLK.Enter
        objLK = cmbLK.SelectedItem
    End Sub

    Private Sub cmbLK_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLK.SelectedIndexChanged
        lblLK_ID.Text = CType(sender.SelectedItem, CDoiTuong).KH
        Try
            If objLK.Ten <> CType(sender.SelectedItem, CDoiTuong).Ten Then
                If RowCount > 0 Then
                    If MessageBox.Show("Chọn Loại kho khác sẽ mất các Mặt Hàng đang có.Bạn có chắc chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
                        dsDataSet.Tables(0).Clear()
                        gridCTPhieu.DataSource = dsDataSet.Tables(0).DefaultView
                    Else
                        'Quay tro lai neu ko chon cai khac
                        cmbLK.SelectedValue = objLK.KH
                        lblLK_ID.Text = objLK.KH
                    End If
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cmbLoaiMH_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLoaiMH.Enter
        objLoaiMH = cmbLoaiMH.SelectedItem
    End Sub

    Private Sub chkTCXacNhan_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkTCXacNhan.CheckedChanged
        If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
            If chkTCXacNhan.Checked Then
                For i As Integer = 0 To RowCount - 1
                    gridCTPhieu.Rows(i).Cells("slth").Value = gridCTPhieu.Rows(i).Cells("slkh").Value
                Next
                lblBCTH.Text = "Đã xác nhận (TC)"
            Else
                For i As Integer = 0 To RowCount - 1
                    gridCTPhieu.Rows(i).Cells("slth").Value = DBNull.Value
                Next
                cmbKyQT.SelectedValue = 1
                lblBCTH.Text = "Chưa xác nhận (KH)"
            End If
        End If
    End Sub
#End Region

#Region "gridCTPhieu"

    Private Sub gridCTPhieu_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles gridCTPhieu.CellBeginEdit
        If e.ColumnIndex = gridCTPhieu.Columns("slkh").Index Then
            gridCTPhieu.Columns("slkh").DefaultCellStyle.Format = Nothing
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("slth").Index Then
            gridCTPhieu.Columns("slth").DefaultCellStyle.Format = Nothing
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("gle").Index Then
            gridCTPhieu.Columns("gle").DefaultCellStyle.Format = Nothing
        End If
    End Sub

    Private Sub gridCTPhieu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gridCTPhieu.KeyDown
        If e.KeyCode = Keys.Enter Then
            If gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("slth").Index And _
            g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                gridCTPhieu.SelectedCells(0).Value = gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("slkh").Value
            End If
            'Kiem tra mat hang da chon het slth hay chua
            'Neu roi thi check = true
            chkTCXacNhan.Checked = CheckTCXacNhan()
        ElseIf e.KeyCode = Keys.Delete Then
            If gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("slth").Index And _
            g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                gridCTPhieu.SelectedCells(0).Value = DBNull.Value
            ElseIf (gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("slkh").Index Or _
            gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("lo").Index Or _
            gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("hansd").Index Or _
            gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("gle").Index) And _
            g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                gridCTPhieu.SelectedCells(0).Value = DBNull.Value
                If gridCTPhieu.SelectedCells(0).ColumnIndex <> gridCTPhieu.Columns("hansd").Index Then
                    gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("thanhtien").Value = DBNull.Value
                    ShowSoKH_TGiaTri()
                End If
            End If
        End If

    End Sub

    Private Sub gridCTPhieu_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridCTPhieu.Enter
        RowCount = GetRowCount()
        ShowSoKH_TGiaTri()
    End Sub

    Private Sub gridCTPhieu_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellEnter
        lblSLTON.Text = ""
        lblNotify.Text = ""
        If (e.ColumnIndex = gridCTPhieu.Columns("slth").Index And g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH)) Or _
        (e.ColumnIndex = gridCTPhieu.Columns("slkh").Index And g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH)) Then
            lblNotify.Text = GetLabelNotify(enumLabelNotify.SLKHColumn)
        ElseIf (e.ColumnIndex = gridCTPhieu.Columns("slkh").Index Or e.ColumnIndex = gridCTPhieu.Columns("slth").Index) And _
        g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
            lblNotify.Text = GetLabelNotify(enumLabelNotify.SLTHColumn)
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("slkh").Index _
            And g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) _
            And enumNX = enumDOITUONG.TINHCHATXUAT Then
            If e.RowIndex = RowCount Or gridCTPhieu.Rows(e.RowIndex).Cells("sltonkh").Value Is DBNull.Value Then
                Exit Sub
            End If
            'Kiem tra ngay them moi co phai la ngay hien tai khong?
            'Neu la ngay hien tai thi lay sltonkh hien tai
            'Neu khong la ngay hien tai thi tinh sltonkh tai thoi diem do
            If dtNgay.Value.Date >= Date.Today Then
                'Kiem tra xem la them phieu moi hay sua phieu
                'neu them phieu moi thi lay slton hien tai
                'nguoc lai sua phieu thi lay slton hien tai truoc khi phieu sua duoc tao moi
                If objPhieu Is Nothing Then
                    Try
                        sltonkh = gridCTPhieu.Rows(e.RowIndex).Cells("sltonkh").Value
                    Catch ex As Exception
                        sltonkh = 0
                    End Try
                Else
                    CMatHangs.GetSLTonDenNgay(objPhieu.DPNX_ID, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                End If
            Else
                'Kiem tra them vao hay sua phieu vao ngay qua khu
                If objPhieu Is Nothing Then
                    CMatHangs.GetSLTonDenNgay(-1, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                Else
                    CMatHangs.GetSLTonDenNgay(objPhieu.DPNX_ID, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                End If
            End If
            If sltonkh > 0 Then
                lblSLTON.Text = "Số lượng tồn kế hoạch đến ngày " + dtNgay.Value.Date.ToString(FormatDateStyle()) + ": " + sltonkh.ToString(FormatQuantityStyle())
            Else
                lblSLTON.Text = "Số lượng tồn kế hoạch đến ngày " + dtNgay.Value.Date.ToString(FormatDateStyle()) + ": 0"
            End If
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("slth").Index _
            And g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) _
            And enumNX = enumDOITUONG.TINHCHATXUAT Then
            'Kiem tra ngay them moi co phai la ngay hien tai khong?
            'Neu la ngay hien tai thi lay sltonth hien tai
            'Neu khong la ngay hien tai thi tinh sltonth tai thoi diem do
            If dtNgay.Value.Date >= Date.Today Then
                If objPhieu Is Nothing Then
                    Try
                        sltonth = gridCTPhieu.Rows(e.RowIndex).Cells("sltonth").Value
                    Catch ex As Exception
                        sltonth = 0
                    End Try
                Else
                    CMatHangs.GetSLTonDenNgay(objPhieu.DPNX_ID, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                End If
            Else
                If objPhieu Is Nothing Then
                    CMatHangs.GetSLTonDenNgay(-1, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                Else
                    CMatHangs.GetSLTonDenNgay(objPhieu.DPNX_ID, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                End If
            End If
            If sltonth > 0 Then
                lblSLTON.Text = "Số lượng tồn thực hiện đến ngày" + dtNgay.Value.Date.ToString(FormatDateStyle()) + ": " + sltonth.ToString(FormatQuantityStyle())
            Else
                lblSLTON.Text = "Số lượng tồn thực hiện đến ngày " + dtNgay.Value.Date.ToString(FormatDateStyle()) + ": 0"
            End If
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("ma").Index And enumNX = enumDOITUONG.TINHCHATNHAP Then
            lblNotify.Text = GetLabelNotify(enumLabelNotify.MaColumn)
        Else
            lblNotify.Text = GetLabelNotify()
        End If
    End Sub

    'Thuc hien khi cap nhat slkh hay slth
    Private Sub gridCTPhieu_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellEndEdit
        If e.ColumnIndex = gridCTPhieu.Columns("slkh").Index Or e.ColumnIndex = gridCTPhieu.Columns("slth").Index Or e.ColumnIndex = gridCTPhieu.Columns("gle").Index Or e.ColumnIndex = gridCTPhieu.Columns("thanhtien").Index Then
            gridCTPhieu.Columns("slkh").DefaultCellStyle.Format = FormatQuantityStyle()
            gridCTPhieu.Columns("slth").DefaultCellStyle.Format = FormatQuantityStyle()
            gridCTPhieu.Columns("gle").DefaultCellStyle.Format = FormatMoneyStyle()
            Dim slkh, slth As Double
            Dim gle As Double
            If gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value IsNot DBNull.Value Then
                If gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value < 0 Then
                    ShowMessages("Số lượng kế hoạch phải > 0")
                    gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = DBNull.Value
                    Exit Sub
                End If
            End If

            If gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value IsNot DBNull.Value Then
                If gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value < 0 Then
                    ShowMessages("Số lượng thực hiện phải > 0")
                    gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value = DBNull.Value
                    Exit Sub
                End If
            End If

            If gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value IsNot DBNull.Value Then
                If gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value < 0 Then
                    ShowMessages("Đơn giá phải > 0")
                    gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value = DBNull.Value
                    Exit Sub
                End If
            End If

            'Lay slkh
            Try
                slkh = gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value
            Catch ex As Exception
                slkh = 0
            End Try

            'Lay slth
            Try
                slth = gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value
            Catch ex As Exception
                slth = 0
            End Try
            If enumNX = enumDOITUONG.TINHCHATXUAT Then
                If slkh > sltonkh Then
                    ShowMessages("Số lượng kế hoạch phải nhỏ hơn số lượng tồn kế hoạch.")
                    gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = 0
                    Exit Sub
                End If

                If slth > sltonth Then
                    ShowMessages("Số lượng thực hiện phải nhỏ hơn số lượng tồn thực hiện.")
                    gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value = 0
                    Exit Sub
                End If
            End If

            'So sanh slth voi slkh
            If slth > 0 And slth <> slkh Then
                gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = slth
                slkh = slth
            End If

            Try
                gle = gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value
            Catch ex As Exception
                gle = 0
            End Try
            '***Phai doi ra dung format truoc khi tinh thanh tien
            If slkh > 0 Then
                slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
            End If
            If gle > 0 Then
                gle = CType(gle.ToString(FormatMoneyStyle()), Double)
            End If

            'Tinh thanh tien sau khi format xong
            Dim thanhtien As Double = slkh * gle
            thanhtien = CType(thanhtien, Long)
            gridCTPhieu.Rows(e.RowIndex).Cells("thanhtien").Value = thanhtien
            ShowSoKH_TGiaTri()

            'Kiem tra mat hang da chon het slth hay chua
            'Neu roi thi check = true
            chkTCXacNhan.Checked = CheckTCXacNhan()
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("hansd").Index Then
            Try
                Dim hsd As String
                Dim strDate(2) As String
                hsd = StrConv(gridCTPhieu.Rows(e.RowIndex).Cells("hansd").Value, VbStrConv.Uppercase)
                If hsd(0).ToString <> "H" Then
                    hsd = hsd.Insert(0, "H")
                End If
                gridCTPhieu.Rows(e.RowIndex).Cells("hansd").Value = hsd
            Catch ex As Exception
                gridCTPhieu.Rows(e.RowIndex).Cells("hansd").Value = DBNull.Value
            End Try
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("makho").Index Then
            'Kiem tra xem makho chon co phai la "Chon tat ca"?
            If gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString() = "0001" Then
                ShowMessages("Phải chọn Kho cụ thể.")
                'reset value
                gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value = DBNull.Value
                'Focus Cell
                'For Each cell As DataGridViewCell In gridCTPhieu.SelectedCells
                '    cell.Selected = False
                'Next
                'gridCTPhieu.Rows(e.RowIndex).Cells("makho").Selected = True
                Exit Sub
            End If

            If enumNX = enumDOITUONG.TINHCHATNHAP Then
                If objPhieu IsNot Nothing Then
                    Dim frm As New frmChonMatHang(CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc, objPhieu.DPNX_ID, dtNgay.Value.Date, cmbLK.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
                    frm.fCallPhieuNX = Me
                    frm.ShowDialog(Me)
                Else
                    Dim frm As New frmChonMatHang(CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc, cmbLK.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
                    frm.fCallPhieuNX = Me
                    frm.ShowDialog(Me)
                End If
            Else
                If cmbLoaiMH.SelectedIndex < 0 Then
                    ShowMessages("Phải chọn Loại Mặt Hàng trước mới có thể thêm mặt hàng")
                    Exit Sub
                End If

                If cmbLK.SelectedIndex < 0 Then
                    ShowMessages("Phải chọn nhập vào Loại Kho trước mới có thể thêm mặt hàng")
                    Exit Sub
                End If

                If gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value Is DBNull.Value Then
                    ShowMessages("Phải chọn Kho chứa mặt hàng trước.")
                    Exit Sub
                End If

                Dim frm As frmLoHang
                If objPhieu IsNot Nothing Then
                    frm = New frmLoHang(objPhieu.DPNX_ID, dtNgay.Value.Date, cmbLK.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
                Else
                    frm = New frmLoHang(cmbLK.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
                End If

                frm.fCallPhieuNX = Me
                frm.ShowDialog(Me)
            End If
            RowCount = GetRowCount()
        End If
    End Sub

    Private Sub gridCTPhieu_UserDeletedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles gridCTPhieu.UserDeletedRow
        RowCount = GetRowCount()
        ShowSoKH_TGiaTri()
    End Sub

    Private Sub gridCTPhieu_UserAddedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles gridCTPhieu.UserAddedRow
        'Cap nhat RowHeader khi add new row
        RowCount = GetRowCount()
        For count As Integer = 0 To RowCount - 1
            gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
        Next
        txtSoKH.Text = RowCount.ToString
    End Sub
#End Region

#Region "Textbox"
    'To mau cho control khi Focus
    Private Sub textBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles txtSoPhieu.Enter, txtDVGN.Enter, txtNgayPH.Enter, dtNgay.Enter, txtTCNX.Enter, txtTheoHD.Enter, txtTheoLenh.Enter, txtNguoiVP.Enter, txtGGT.Enter, txtNgayKGGT.Enter, txtSoKH.Enter, txtTrLuong.Enter, txtSoKien.Enter, txtTGiaTri.Enter, txtNguoiGN.Enter, txtNgayGN.Enter
        Try
            SetColorAllControls(sender, True)
            If (CType(sender, TextBox) Is txtDVGN) Or (CType(sender, TextBox) Is txtTCNX) Or (CType(sender, TextBox) Is txtTheoHD) Then
                If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                    lblNotify.Text = GetLabelNotify(enumLabelNotify.DOITUONG)
                End If
            End If
            If (sender Is txtSoKH) Or (sender Is txtSoKien) Or (sender Is txtTrLuong) Then
                Dim txt As TextBox = CType(sender, TextBox)
                txt.Text = CInt(txt.Text).ToString()
            End If
        Catch ex As Exception
        End Try
    End Sub

    Private Sub txtSoPhieu_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSoPhieu.KeyPress, txtTheoLenh.KeyPress, txtNguoiVP.KeyPress, txtNguoiGN.KeyPress
        If sender Is txtSoPhieu Then
            e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString, VbStrConv.Uppercase))
        Else
            If CType(sender, TextBox).Text.Length = 0 Then
                e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString, VbStrConv.ProperCase))
            End If
        End If
    End Sub

    Private Sub textBox_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles txtNgayPH.Leave, dtNgay.Leave, txtTheoLenh.Leave, txtNguoiVP.Leave, txtGGT.Leave, txtNgayKGGT.Leave, txtSoKH.Leave, txtTrLuong.Leave, txtSoKien.Leave, txtTGiaTri.Leave, txtNguoiGN.Leave, txtNgayGN.Leave
        SetColorAllControls(sender, False)
        lblNotify.Text = GetLabelNotify()
        If (sender Is txtSoKH) Or (sender Is txtSoKien) Or (sender Is txtTrLuong) Then
            Dim txt As TextBox = CType(sender, TextBox)
            Try
                txt.Text = Format(CInt(txt.Text), FormatQuantityStyle())
            Catch ex As Exception
                txt.Text = 0
            End Try
        End If
    End Sub

    ''' <summary>
    ''' Update: 25-01-2010
    ''' Kiểm tra số phiếu có bị trùng không
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtSoPhieu_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSoPhieu.Leave
        SetColorAllControls(sender, False)
        lblNotify.Text = GetLabelNotify()
        'Kiem tra phieu nay da ton tai chua
        Dim sophieu As String = txtSoPhieu.Text.Trim()
        If objPhieu Is Nothing Then
            If CPhieuNXs.IsExist(enumNX, sophieu) Then
                ShowMessages("Số phiếu này bị trùng.")
                txtSoPhieu.Focus()
            End If
        Else
            If CPhieuNXs.IsExist(enumNX, sophieu, objPhieu.DPNX_ID) Then
                ShowMessages("Số phiếu này bị trùng.")
                txtSoPhieu.Focus()
            End If
        End If
    End Sub

    Private Sub txtDoiTuong_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVGN.DoubleClick, txtTCNX.DoubleClick
        If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
            If sender Is txtDVGN Then
                ShowFormDoiTuong(enumDOITUONG.DONVI, txtDVGN.Text)
            Else
                ShowFormDoiTuong(enumNX, txtTCNX.Text)
            End If
        End If
    End Sub

    Private Sub txtDoiTuong_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDVGN.KeyDown, txtTCNX.KeyDown, txtTheoHD.KeyDown
        If e.KeyCode = Keys.F1 Then
            If sender Is txtDVGN Then
                txtDoiTuong_DoubleClick(sender, Nothing)
            ElseIf sender Is txtTCNX Then
                txtDoiTuong_DoubleClick(sender, Nothing)
            Else
                txtTheoHD_DoubleClick(Nothing, Nothing)
            End If
        End If
    End Sub

    Private Sub txtTheoHD_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTheoHD.DoubleClick
        If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
            Dim frm As New frmHopDong()
            frm.bCallForm = True
            frm.ShowDialog()
            If frm.selectedHD IsNot Nothing Then
                txtTheoHD.Text = frm.selectedHD.SOHOPDONG
            Else
                txtTheoHD.Text = ""
            End If
        End If
    End Sub

    Private Sub txtTheoHD_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTheoHD.Leave
        SetColorAllControls(sender, False)
        lblNotify.Text = GetLabelNotify()

        Dim strTen As String = txtTheoHD.Text
        If strTen <> "" Then
            Dim strSql As String = "sohopdong like N'" + strTen + "'"
            Dim arrFind As ArrayList = CHopDongs.GetHopDongList(strSql)
            If arrFind.Count = 0 Then
                Dim frm As New frmHopDong
                frm.bCallForm = True
                frm.ShowDialog()
                If frm.selectedHD IsNot Nothing Then
                    txtTheoHD.Text = frm.selectedHD.SOHOPDONG
                Else
                    txtTheoHD.Text = ""
                End If
            End If
        End If
    End Sub

    Private Sub txtDoiTuong_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVGN.Leave, txtTCNX.Leave
        SetColorAllControls(sender, False)
        lblNotify.Text = GetLabelNotify()

        Dim loai As enumDOITUONG
        If sender Is txtDVGN Then
            loai = enumDOITUONG.DONVI
        Else
            loai = enumNX
        End If
        Dim strTen As String = CType(sender, TextBox).Text

        If strTen <> "" Then
            Dim arrFind As ArrayList = CDoiTuongs.SearchDoiTuong(loai, strTen)
            If arrFind.Count = 0 Then
                ShowFormDoiTuong(loai, strTen)
            ElseIf arrFind.Count = 1 Then
                Dim objDoiTuong As CDoiTuong = CType(arrFind(0), CDoiTuong)
                Select Case sender.Name
                    Case txtDVGN.Name
                        lblDVGN_ID.Text = objDoiTuong.KH
                        txtDVGN.Text = objDoiTuong.Ten
                    Case txtTCNX.Name
                        lblTCNX_ID.Text = objDoiTuong.KH
                        txtTCNX.Text = objDoiTuong.Ten
                End Select
            End If
        Else 'Neu strTen = "" thi xoa ID trong label
            Select Case sender.Name
                Case txtDVGN.Name
                    lblDVGN_ID.Text = ""
                Case txtTCNX.Name
                    lblTCNX_ID.Text = ""
            End Select
        End If
    End Sub

    Private Sub txtNgayKGGT_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNgayKGGT.Leave
        If Not KiemTraNgayHopLe(txtNgayKGGT.Text) Then
            ShowError("Ngày không hợp lệ")
            txtNgayKGGT.Focus()
        End If
    End Sub

    Private Sub txtNgayGN_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNgayGN.Leave
        If Not KiemTraNgayHopLe(txtNgayGN.Text) Then
            ShowError("Ngày không hợp lệ")
            txtNgayGN.Focus()
        End If
    End Sub

    Private Sub txtNgayPH_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNgayPH.Leave
        If Not KiemTraNgayHopLe(txtNgayPH.Text) Then
            ShowError("Ngày không hợp lệ.")
            txtNgayPH.Focus()
        End If
    End Sub
#End Region

#Region "Button"
    Private Sub btnCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhat.Click, btnCapnhatNew.Click
        Try
            If RowCount = 0 Then
                ShowMessages("Chưa nhập các mặt hàng.")
                Exit Sub
            End If
            'Kiem tra them phieu hay cap nhap phieu
            If objPhieu Is Nothing Then
                If Not InsertDPNX() Then
                    Exit Sub
                End If
            Else
                If Not UpdateDPNX() Then
                    Exit Sub
                End If
            End If
            Dim btn As Button = CType(sender, Button)
            'Neu la btn Cap nhat
            If btn Is btnCapNhat Then
                If fViewPhieuNX IsNot Nothing Then
                    fViewPhieuNX.RefreshForm()
                End If

                If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                    Me.Close()
                End If
            Else 'Neu la Cap nhat va create new
                objPhieu = Nothing
                Init()
            End If
        Catch ex As Exception
            ShowMessages(ex.ToString())
        End Try
    End Sub

    Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        If MessageBox.Show("Bạn có chắc thoát?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            If fViewPhieuNX IsNot Nothing Then
                fViewPhieuNX.RefreshForm()
            End If
            Me.Close()
        End If
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        If objPhieu IsNot Nothing Then
            If MessageBox.Show("Bạn có chắc là xóa phiếu này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                If objPhieu.Delete() > 0 Then
                    ShowMessages("Xong.")
                    If fViewPhieuNX IsNot Nothing Then
                        fViewPhieuNX.RefreshForm()
                    End If
                    Me.Close()
                End If
            End If
        End If
    End Sub
#End Region

    'Private Sub btnInPhieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInPhieu.Click
    '    If objPhieu Is Nothing Then
    '        Exit Sub
    '    End If
    '    Dim objSelectedPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(objPhieu.DPNX_ID)
    '    Dim strSql As String
    '    strSql = "select * from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString()
    '    Dim ds As DataSet
    '    ds = BaseDB.ExecSql_DataSet(strSql)

    '    Dim ten_dvgn, ten_lk, ten_tcnx As String
    '    ten_dvgn = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
    '    ten_lk = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
    '    Dim nnreport As New rptPhieuNhapKho
    '    nnreport.SetDataSource(ds.Tables(0))
    '    nnreport.SetParameterValue("ten_dvgn", ten_dvgn)
    '    nnreport.SetParameterValue("ten_lk", ten_lk)
    '    nnreport.SetParameterValue("tien_chu", DoiSoRaChu(objSelectedPhieu.TGIATRI))
    '    If (objSelectedPhieu.NX = "N") Then
    '        ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, objSelectedPhieu.TCNX).Ten
    '        nnreport.SetParameterValue("loai_phieu", "N")
    '    Else
    '        ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, objSelectedPhieu.TCNX).Ten
    '        nnreport.SetParameterValue("loai_phieu", "X")
    '    End If
    '    nnreport.SetParameterValue("ten_tcnx", ten_tcnx)
    '    Dim frm As New frmReportViewer(nnreport)
    '    frm.ShowDialog()
    'End Sub

    Private Sub btnInPhieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInPhieu.Click
        If objPhieu Is Nothing Then
            Exit Sub
        End If
        Dim objSelectedPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(objPhieu.DPNX_ID)
        Dim strSql As String
        strSql = "select * from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString()
        strSql &= " order by kho, ma"
        Dim ds As DataSet
        Dim count As Integer = 0
        Dim RowCount As Integer = 0
        ds = BaseDB.ExecSql_DataSet(strSql)
        count = ds.Tables(0).Rows.Count * 2
        strSql = "select distinct kho from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString()
        count += BaseDB.ExecSql_DataSet(strSql).Tables(0).Rows.Count
        RowCount = count
        Dim ten_dvgn, ten_lk, ten_tcnx As String
        ten_dvgn = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
        ten_lk = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
        Dim nnreport As New rptPhieuNhapKho
        nnreport.SetDataSource(ds.Tables(0))
        nnreport.SetParameterValue("ten_dvgn", ten_dvgn)
        nnreport.SetParameterValue("ten_lk", ten_lk)
        nnreport.SetParameterValue("tien_chu", DoiSoRaChu(objSelectedPhieu.TGIATRI))
        If (objSelectedPhieu.NX = "N") Then
            ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, objSelectedPhieu.TCNX).Ten
            nnreport.SetParameterValue("loai_phieu", "N")
        Else
            ten_tcnx = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, objSelectedPhieu.TCNX).Ten
            nnreport.SetParameterValue("loai_phieu", "X")
        End If
        nnreport.SetParameterValue("ten_tcnx", ten_tcnx)

        '************************************************************************************************
        'Cau truc mot report cua phieu nhap xuat nhu sau:                                               *
        'Tong kich thuoc 1 trang A4 ~ 11154 (tinh dua vao tong cac section va cac mat hang co toi da)   *
        '1) Section1: 2880                                                                              *
        '2) Section2: 1114                                                                              *
        '3) PageHeaderSection1: 1080                                                                    *
        '       _ GroupHeaderSection2: 327 * N (N: Số Kho được nhập vào trong phiếu)                    *
        '           + Section3: 654*N (N: Số mặt hàng trong phiếu)                                      *
        '4) ReportFooterSection2: 654                                                                   *
        '5) ReportFooterSection1: 3230                                                                  *
        '                                                                                               *
        ' Dựa vào các Height của các Section trên ta tính được                                          *
        ' a)Trang dau: co toi da 22 dong gom mat hang va kho                                            *
        ' b)Trang giua: co toi da 27 dong gom mat hang va kho                                           *
        ' c)Trang cuoi: co toi da 15 dong gom mat hang va kho                                           *
        ' Nhung trong lap trinh thi moi trang nhu vay nen bo mot 1 dong tru hao. Do do:                 *
        ' Trang dau: 21 dong                                                                            *
        ' Trang giua: 27 dong trang giua ko can bot                                                     *
        ' Trang cuoi: 14 dong                                                                           *
        '************************************************************************************************

        Dim Section1 As Section = nnreport.ReportDefinition.Sections("Section1")
        Dim Section2 As Section = nnreport.ReportDefinition.Sections("Section2")
        Dim PageHeaderSection1 As Section = nnreport.ReportDefinition.Sections("PageHeaderSection1")
        Dim GroupHeaderSection2 As Section = nnreport.ReportDefinition.Sections("GroupHeaderSection2")
        Dim Section3 As Section = nnreport.ReportDefinition.Sections("Section3")
        Dim ReportFooterSection2 As Section = nnreport.ReportDefinition.Sections("ReportFooterSection2")
        Dim ReportFooterSection1 As Section = nnreport.ReportDefinition.Sections("ReportFooterSection1")
        Dim height As Integer = GroupHeaderSection2.Height
        If count > 22 Then
            Dim frmPrint As New frmPrintParamater("Số dòng mỗi trang", 27, "Số dòng còn thiếu", 0)
            frmPrint.ShowDialog()
            Dim value As Integer = frmPrint.value
            value = (value * height) / count
            GroupHeaderSection2.Height += value
            Section3.Height += value * 2
        Else
            'If count > 10 Then
            '    Section1.Height += height * 2
            '    PageHeaderSection1.Height += height
            '    'Do Section1 cong them 2*GroupHeaderSection2.Height
            '    'Va PageHeaderSection1 cong them GroupHeaderSection2.Height
            '    'nen ta ko lay 22 dong cua trang dau ma lay 22 dong - count
            '    Dim value As Integer = 22 - count
            '    value = (value * height) / count
            '    GroupHeaderSection2.Height += value
            '    Section3.Height += value * 2
            'ElseIf count = 10 Then
            '    ReportFooterSection1.Height -= 278
            'End If
            If count > 10 And count <= 19 Then
                Section1.Height += height * 2
                PageHeaderSection1.Height += height
                'Do Section1 cong them 2*GroupHeaderSection2.Height
                'Va PageHeaderSection1 cong them GroupHeaderSection2.Height
                'nen ta ko lay 22 dong cua trang dau ma lay 19 dong - count
                Dim value As Integer = 19 - count
                value = (value * height) / count
                GroupHeaderSection2.Height += value
                Section3.Height += value * 2
            ElseIf count > 19 Then
                Dim value As Integer = 22 - count
                value = (value * height) / count
                GroupHeaderSection2.Height += value
                Section3.Height += value * 2
            ElseIf count = 10 Then
                ReportFooterSection1.Height -= 278
            End If
        End If
        Dim frm As New frmReportViewer(nnreport)
        frm.ShowDialog()
    End Sub
#End Region

#Region "Functions"
    'Ham nay dung de hien thi huong dan cho nguoi su dung
    Public Function GetLabelNotify(Optional ByVal eNotify As enumLabelNotify = enumLabelNotify.None) As String
        Dim str As String = ""
        Select Case eNotify
            Case enumLabelNotify.DOITUONG, enumLabelNotify.MaColumn
                str = "Nhấn F1 hoặc đúp chuột để chọn"
            Case enumLabelNotify.HSDColumn
                str = "Nhập HSD là 4 ký tự số. Ví dụ: 1008 sẽ ra 10/08"
            Case enumLabelNotify.SLKHColumn
                str = "Bạn không có quyền sửa cột này"
            Case enumLabelNotify.SLTHColumn
                str = "Nhấn Enter để xác nhận số lượng của kế hoạch."
        End Select
        Return str
    End Function

    Public Sub InitPhieuNhap()
        enumNX = enumDOITUONG.TINHCHATNHAP
        Me.Text = "Phiếu nhập"
        lblDVGN.Text = "Đơn vị giao"
        lblTCNX.Text = "Tính chất nhập"
        'lblTheoLenh.Text = "Theo hóa đơn số"
        lblLK.Text = "Nhập vào Kho hàng"
        lblNguoiGN.Text = "&Người giao"
        lblNgayGN.Text = "Ngày nhập kho"
        lblGGT.Visible = False
        txtGGT.Visible = False
        lblNgayKGGT.Visible = False
        txtNgayKGGT.Visible = False

        If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
            Panel2.Height -= 30
            lblSLTON.Visible = False
            chkTCXacNhan.Visible = False
            lblKyQT.Visible = False
            cmbKyQT.Visible = False
            lblHTTT.Visible = False
            cmbHTTT.Visible = False
            gridCTPhieu.AllowUserToAddRows = True
        ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
            gridCTPhieu.AllowUserToAddRows = False
            lblHTTT.Visible = True
            cmbHTTT.Visible = True
            lblKyQT.Visible = True
            cmbKyQT.Visible = True

            Dim ds As DataSet = BaseDB.ExecSql_DataSet("select * from tblKyQT")
            cmbKyQT.DisplayMember = "tenkyqt"
            cmbKyQT.ValueMember = "id"
            cmbKyQT.DataSource = ds.Tables(0)

            'Disable cac control ko cho Tai chinh chinh sua
            cmbLoaiMH.Enabled = False
            cmbLK.Enabled = False
            dtNgay.Enabled = False

            txtSoPhieu.ReadOnly = True
            txtNgayPH.ReadOnly = True
            txtDVGN.ReadOnly = True
            txtTCNX.ReadOnly = True
            txtTheoLenh.ReadOnly = True
            txtNguoiVP.ReadOnly = True
            txtTheoHD.ReadOnly = True
            txtNguoiGN.ReadOnly = True
            txtGGT.ReadOnly = True
            txtNgayKGGT.ReadOnly = True
            txtNgayGN.ReadOnly = True
            txtSoKien.ReadOnly = True
            txtTrLuong.ReadOnly = True
        End If
    End Sub

    Public Sub InitPhieuXuat()
        enumNX = enumDOITUONG.TINHCHATXUAT
        Me.Text = "Phiếu xuất"
        lblDVGN.Text = "Đơn vị nhận"
        lblTCNX.Text = "Tính chất xuất"
        'lblTheoLenh.Text = "Theo hóa đơn số"
        lblLK.Text = "Xuất từ Kho hàng"
        lblNguoiGN.Text = "&Người nhận"
        lblNgayGN.Text = "Ngày nhận hàng"
        lblGGT.Visible = True
        txtGGT.Visible = True
        lblNgayKGGT.Visible = True
        txtNgayKGGT.Visible = True
        txtTheoHD.Visible = False
        lblTheoHD.Visible = False
        gridCTPhieu.AllowUserToAddRows = True
        If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
            lblHTTT.Visible = False
            cmbHTTT.Visible = False
            lblKyQT.Visible = False
            cmbKyQT.Visible = False
            gridCTPhieu.AllowUserToAddRows = True
        ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
            gridCTPhieu.AllowUserToAddRows = False
            lblHTTT.Visible = True
            cmbHTTT.Visible = True
            lblKyQT.Visible = True
            cmbKyQT.Visible = True

            Dim ds As DataSet = BaseDB.ExecSql_DataSet("select * from tblKyQT")
            cmbKyQT.DisplayMember = "tenkyqt"
            cmbKyQT.ValueMember = "id"
            cmbKyQT.DataSource = ds.Tables(0)

            'Disable cac control ko cho Tai chinh chinh sua
            cmbLoaiMH.Enabled = False
            cmbLK.Enabled = False
            dtNgay.Enabled = False

            txtSoPhieu.ReadOnly = True
            txtNgayPH.ReadOnly = True
            txtDVGN.ReadOnly = True
            txtTCNX.ReadOnly = True
            txtTheoLenh.ReadOnly = True
            txtNguoiVP.ReadOnly = True
            txtTheoHD.ReadOnly = True
            txtNguoiGN.ReadOnly = True
            txtGGT.ReadOnly = True
            txtNgayKGGT.ReadOnly = True
            txtNgayGN.ReadOnly = True
            txtSoKien.ReadOnly = True
            txtTrLuong.ReadOnly = True
        End If
    End Sub

    Public Sub Init()
        If objPhieu IsNot Nothing Then
            If objPhieu.NX = "N" Then
                InitPhieuNhap()
            Else
                InitPhieuXuat()
            End If
            With objPhieu
                objLoaiMH = CLoaiThuocs.GetLoaiThuocByMa(.LOAIMH)
                cmbLoaiMH.SelectedValue = .LOAIMH

                txtSoPhieu.Text = .SOPHIEU
                If .NGAYPH = "1/1/2001" Then
                    txtNgayPH.Text = ""
                Else
                    txtNgayPH.Text = Format(.NGAYPH, FormatDateStyle())
                End If

                lblDVGN_ID.Text = .DVGN
                txtDVGN.Text = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, .DVGN).Ten
                lblTCNX_ID.Text = .TCNX
                txtTCNX.Text = CDoiTuongs.GetDoiTuongByMa(enumNX, .TCNX).Ten

                lblLK_ID.Text = .LK
                cmbLK.SelectedValue = .LK

                txtTheoLenh.Text = .THEOLENH
                txtTheoHD.Text = CHopDongs.GetHopDongByMa(.HOPDONG).SOHOPDONG
                txtNguoiGN.Text = .NGUOIGN
                txtGGT.Text = .GGT
                If .NGAYKGGT = DateNull() Then
                    txtNgayKGGT.Text = ""
                Else
                    txtNgayKGGT.Text = Format(.NGAYKGGT, FormatDateStyle())
                End If

                If .NGAYGN = DateNull() Then
                    txtNgayGN.Text = ""
                Else
                    txtNgayGN.Text = Format(.NGAYGN, FormatDateStyle())
                End If

                txtNguoiVP.Text = .NGUOIVP
                dtNgay.Value = .NGAY
                txtSoKH.Text = .SOKH.ToString(FormatQuantityStyle())
                txtSoKien.Text = .SOKIEN.ToString(FormatQuantityStyle())
                txtTrLuong.Text = .TRLUONG.ToString(FormatQuantityStyle())
                Try
                    cmbHTTT.SelectedIndex = .HTTT - 1
                Catch ex As Exception
                    cmbHTTT.SelectedIndex = -1
                End Try

                Try
                    txtTGiaTri.Text = .TGIATRI.ToString(FormatMoneyStyle())
                Catch ex As Exception
                    txtTGiaTri.Text = "0"
                End Try

                Dim objBCTH As CBCTH
                objBCTH = CBCTHs.GetBCTH(.BCTH, .TCSL)
                If .BCTH = enumBCTH.KH Then
                    lblBCTH.Text = "Chưa xác nhận (KH)"
                ElseIf .BCTH = enumBCTH.TC Then
                    lblBCTH.Text = "Đã xác nhận (TC)"
                    chkTCXacNhan.Checked = True
                End If

                Try
                    cmbKyQT.SelectedValue = .KYQT
                Catch ex As Exception
                    cmbKyQT.SelectedValue = 1
                End Try
            End With
        Else
            btnXoa.Enabled = False
            cmbLoaiMH.SelectedIndex = 4
            txtSoPhieu.Text = ""
            txtNgayPH.Text = ""
            lblDVGN_ID.Text = ""
            txtDVGN.Text = ""
            lblTCNX_ID.Text = ""
            txtTCNX.Text = ""
            cmbLK.SelectedIndex = 0

            txtTheoLenh.Text = ""
            txtNguoiGN.Text = ""
            txtGGT.Text = ""
            txtNgayKGGT.Text = ""
            txtNgayGN.Text = ""
            txtNguoiVP.Text = g_User.FullName
            dtNgay.Text = ""
            txtSoKH.Text = ""
            txtSoKien.Text = ""
            txtTrLuong.Text = ""
            cmbHTTT.SelectedIndex = 0
            txtTGiaTri.Text = ""
            lblBCTH.Text = "Chưa xác nhận (KH)"
            cmbKyQT.SelectedValue = 1
            If enumNX = enumDOITUONG.TINHCHATNHAP Then
                InitPhieuNhap()
            Else
                InitPhieuXuat()
            End If
            lblSLTON.Text = ""
        End If
        FormatGridStyleCTPhieuNhap()
        ControlSetFocus(cmbLoaiMH)
    End Sub

    'Ham nay dung de hien thi danh muc DVGN va TCNX de chon gia tri
    Public Sub ShowFormDoiTuong(ByVal loai As enumDOITUONG, ByVal value As String)
        Dim frm As New frmDMDoiTuong
        Select Case loai
            Case enumDOITUONG.DONVI
                frm.Text = "Chọn đơn vị"
            Case enumDOITUONG.TINHCHATNHAP
                frm.Text = "Chọn Tính chất nhập"
            Case enumDOITUONG.TINHCHATXUAT
                frm.Text = "Chọn Tính chất xuất"
        End Select
        frm.bCallForm = True
        frm.eDoiTuong = loai
        frm.sFind = value
        frm.ShowDialog()
        If frm.selectedDT IsNot Nothing Then
            Select Case loai
                Case enumDOITUONG.DONVI
                    lblDVGN_ID.Text = frm.selectedDT.KH
                    txtDVGN.Text = frm.selectedDT.Ten
                Case enumDOITUONG.TINHCHATNHAP, enumDOITUONG.TINHCHATXUAT
                    If CDoiTuongs.KiemTraTCNX(enumTCNX.DCSS, frm.selectedDT.KH) Then
                        Dim str As String = "Tính chất " + frm.selectedDT.Ten + " được chọn ở form Điều chỉnh số lượng sổ sách"
                        ShowMessages(str)
                        Exit Sub
                    End If
                    lblTCNX_ID.Text = frm.selectedDT.KH
                    txtTCNX.Text = frm.selectedDT.Ten
            End Select
        Else
            Select Case loai
                Case enumDOITUONG.DONVI
                    lblDVGN_ID.Text = ""
                    txtDVGN.Text = ""
                Case enumDOITUONG.TINHCHATNHAP, enumDOITUONG.TINHCHATXUAT
                    lblTCNX_ID.Text = ""
                    txtTCNX.Text = ""
            End Select
        End If
    End Sub

    Public Function PopulatePhieuInfo() As Boolean
        Dim len As Integer = 0
        With objPhieu
            .NX = LocNhapXuat(enumNX)
            If cmbLoaiMH.SelectedIndex < 0 Then
                ShowMessages("Chưa chọn loại mặt hàng")
                If cmbLoaiMH.CanFocus Then
                    cmbLoaiMH.Focus()
                End If
                Return False
            Else
                .LOAIMH = CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc
            End If

            'Kiểm tra phiếu co empty không
            If txtSoPhieu.Text = "" Then
                ShowMessages("Số phiếu chưa nhập.")
                If txtSoPhieu.CanFocus Then
                    txtSoPhieu.Focus()
                End If
                Return False
            Else
                'Kiểm tra số phiếu có bị trùng không

                .SOPHIEU = txtSoPhieu.Text
            End If

            'Kiểm tra độ dài phiếu hợp lệ
            len = .ColumnLength("sophieu")
            If len < .SOPHIEU.Length Then
                ShowMessages("Chiều dài ký tự Số phiếu vượt quá " + len.ToString())
                txtSoPhieu.Focus()
                Return False
            End If

            Try
                .NGAYPH = ConvertStringTypeToDateType(txtNgayPH.Text)
            Catch ex As Exception
                .NGAYPH = CDate("1/1/2001")
            End Try

            .DVGN = CDoiTuongs.GetDoiTuongByTen(enumDOITUONG.DONVI, txtDVGN.Text).KH
            If .DVGN Is Nothing Then
                If enumNX = enumDOITUONG.TINHCHATNHAP Then
                    ShowError("Đơn vị giao chưa chọn.")
                Else
                    ShowError("Đơn vị nhận chưa chọn.")
                End If
                If txtDVGN.CanFocus Then
                    txtDVGN.Focus()
                End If
                Return False
            End If

            'Chi kiem tra TCNX doi voi truong hop lap phieu nhap
            'Phieu xuat khong can TCNX
            .TCNX = CDoiTuongs.GetDoiTuongByTen(enumNX, txtTCNX.Text).KH
            If .TCNX Is Nothing And enumNX = enumDOITUONG.TINHCHATNHAP Then
                ShowError("Tính chất nhập chưa chọn.")
                If txtTCNX.CanFocus Then
                    txtTCNX.Focus()
                End If
                Return False
            End If

            .LK = CType(cmbLK.SelectedItem, CDoiTuong).KH
            If .LK Is Nothing Then
                ShowError("Loại kho chưa chọn.")
                Return False
            End If

            .THEOLENH = txtTheoLenh.Text
            'Kiểm tra độ dài theo lệnh hợp lệ
            len = .ColumnLength("theolenh")
            If len < .THEOLENH.Length Then
                ShowMessages("Chiều dài ký tự của Theo lệnh vượt quá " + len.ToString())
                txtTheoLenh.Focus()
                Return False
            End If

            Try
                .HOPDONG = CHopDongs.GetHopDongBySoHD(txtTheoHD.Text).HOPDONG_ID
            Catch ex As Exception
                .HOPDONG = Nothing
            End Try

            .NGUOIGN = txtNguoiGN.Text
            len = .ColumnLength("nguoign")
            If len < .NGUOIGN.Length Then
                ShowMessages("Chiều dài ký tự của Người GN vượt quá " + len.ToString())
                txtNguoiGN.Focus()
                Return False
            End If

            .GGT = txtGGT.Text
            len = .ColumnLength("ggt")
            If len < .GGT.Length Then
                ShowMessages("Chiều dài ký tự của GGT vượt quá " + len.ToString())
                txtGGT.Focus()
                Return False
            End If

            Try
                .NGAYKGGT = ConvertStringTypeToDateType(txtNgayKGGT.Text)
            Catch ex As Exception
                .NGAYKGGT = DateNull()
            End Try

            Try
                .NGAYGN = ConvertStringTypeToDateType(txtNgayGN.Text)
            Catch ex As Exception
                .NGAYGN = DateNull()
            End Try

            .NGUOIVP = txtNguoiVP.Text
            len = .ColumnLength("nguoivp")
            If len < .NGUOIVP.Length Then
                ShowMessages("Chiều dài ký tự của Người VP vượt quá " + len.ToString())
                txtNguoiVP.Focus()
                Return False
            End If

            .NGAY = Me.dtNgay.Value.Date

            Try
                .SOKH = GetRowCount()
            Catch ex As Exception
                .SOKH = 0
            End Try

            Try
                .SOKIEN = CUInt(txtSoKien.Text)
            Catch ex As Exception
                .SOKIEN = Nothing
            End Try

            Try
                .TRLUONG = Double.Parse(txtTrLuong.Text)
            Catch ex As Exception
                .TRLUONG = Nothing
            End Try

            Try
                .TGIATRI = CType(txtTGiaTri.Text, Double)
            Catch ex As Exception
                .TGIATRI = 0
            End Try

            If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                .HTTT = Nothing
                .KYQT = 1
                .BCTH = 1
            ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                Dim objHTTT As CDoiTuong
                objHTTT = cmbHTTT.SelectedItem
                Try
                    .HTTT = objHTTT.KH
                Catch ex As Exception
                    .HTTT = Nothing
                End Try

                If chkTCXacNhan.Checked Then
                    .BCTH = 2
                    .KYQT = cmbKyQT.SelectedValue
                Else
                    .BCTH = 1
                    .KYQT = 1
                End If
            End If

            If txtNgayPH.Text <> "  /  /" Then
                If .NGAYPH < .NGAY Then
                    ShowMessages("Thời hạn phiếu phải > Ngày lập phiếu")
                    If txtNgayPH.CanFocus Then
                        txtNgayPH.Focus()
                    End If
                    Return False
                End If
            End If
        End With
        Return True
    End Function

    'Public Sub setFocusCell(ByRef _griddViewCell As DataGridViewCell)
    '    For Each cell As DataGridViewCell In gridCTPhieu.SelectedCells
    '        cell.Selected = False
    '    Next
    '    _griddViewCell.Selected = True
    'End Sub

    Public Sub FormatGridStyleCTPhieuNhap()
        sdaSLNX = Nothing
        dsDataSet = Nothing
        Try
            sdaSLNX = g_objConnFactory.CreateAdapter
            CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet, objPhieu.DPNX_ID)
        Catch ex As Exception
            CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet, Nothing)
        End Try
        Dim dv As DataView
        dv = dsDataSet.Tables(0).DefaultView
        gridCTPhieu.DataSource = dv

        With gridCTPhieu
            'Frozen
            'Column Combobox makho da set Frozen = True trong luc tao
            .Columns.Item("kho").Frozen = True
            .Columns.Item("ten").Frozen = True
            .Columns.Item("lo").Frozen = True

            'Header text and format cellstyle
            .Columns.Item("kho").HeaderText = "Kho"
            .Columns.Item("ma").HeaderText = "Mã"
            .Columns.Item("code").HeaderText = "Code"
            .Columns.Item("ten").HeaderText = "Tên hàng"
            .Columns.Item("lo").HeaderText = "Lô hàng"
            .Columns.Item("dvt").HeaderText = "Đvt"
            .Columns.Item("hansd").HeaderText = "Hạn SD"
            .Columns.Item("h").HeaderText = "CCL"
            .Columns.Item("ghichu").HeaderText = "Ghi chú"
            With .Columns.Item("slkh")
                .HeaderText = "SL Kế hoạch"
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightGreen
            End With
            With .Columns.Item("slth")
                .HeaderText = "SL Thực hiện"
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
            End With
            With .Columns.Item("gle")
                .HeaderText = "Đơn giá"
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With
            With .Columns.Item("thanhtien")
                .HeaderText = "Thành tiền"
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            'Hide những column ko cần thiết
            .Columns.Item("mathang_id").Visible = False
            .Columns.Item("slnx_id").Visible = False
            .Columns.Item("lk").Visible = False
            .Columns.Item("dpnx_id").Visible = False
            .Columns.Item("ma").Visible = False
            .Columns.Item("code").Visible = False
            .Columns.Item("ngtton").Visible = False
            .Columns.Item("slss11").Visible = False
            .Columns.Item("slkk11").Visible = False
            .Columns.Item("sltonkh").Visible = False
            .Columns.Item("sltonth").Visible = False
            .Columns.Item("sltonss").Visible = False

            'Read Only column
            .Columns.Item("dvt").ReadOnly = True
            .Columns.Item("thanhtien").ReadOnly = True
            'Kiem tra phan quyen va chi cho nhap column phu hop
            If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                .Columns.Item("slth").ReadOnly = True
            ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                .Columns.Item("slkh").ReadOnly = True
            End If

            If enumNX = enumDOITUONG.TINHCHATNHAP Then
                If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                    .Columns.Item("makho").Visible = True 'hiển thị mã kho để tạo combobox cho danh mục kho chọn
                    .Columns.Item("kho").Visible = False 'hide tên kho vì đã có combobox chọn kho rồi
                    .Columns.Item("slth").Visible = False 'hide slth vì ban ke hoach chi nhap slkh
                    AddComboBoxColumns_Kho()
                    AddComboBoxColumns_CCL()
                Else
                    .Columns.Item("makho").Visible = False 'hide mã kho vì xuất không cần chọn kho trong datagrid
                    .Columns.Item("kho").Visible = True  'hiển thị tên kho

                    .Columns.Item("kho").ReadOnly = True
                    .Columns.Item("ten").ReadOnly = True
                    .Columns.Item("lo").ReadOnly = True
                    .Columns.Item("hansd").ReadOnly = True
                    .Columns.Item("h").ReadOnly = True
                    .Columns.Item("gle").ReadOnly = True
                    .Columns.Item("slkh").ReadOnly = True
                End If
            Else
                If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                    .Columns.Item("makho").Visible = True 'hiển thị mã kho để tạo combobox cho danh mục kho chọn
                    .Columns.Item("kho").Visible = False 'hide tên kho vì đã có combobox chọn kho rồi
                    .Columns.Item("slth").Visible = False 'hide slth vì ban ke hoach chi nhap slkh
                    AddComboBoxColumns_Kho()
                Else
                    .Columns.Item("makho").Visible = False 'hide mã kho vì xuất không cần chọn kho trong datagrid
                    .Columns.Item("kho").Visible = True  'hiển thị tên kho
                End If
                .Columns.Item("kho").ReadOnly = True
                .Columns.Item("ten").ReadOnly = True
                .Columns.Item("lo").ReadOnly = True
                .Columns.Item("hansd").ReadOnly = True
                .Columns.Item("h").ReadOnly = True
                .Columns.Item("gle").ReadOnly = True

            End If
            RowCount = GetRowCount()
            For count As Integer = 0 To RowCount - 1
                gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
            Next
        End With
        ShowSoKH_TGiaTri()
    End Sub

    ''Kiem tra xem mat hang can chon da chon chua
    'Private Function isNewMatHang(ByVal mathang_id As Integer) As Boolean
    '    For Each dr As DataGridViewRow In gridCTPhieu.Rows
    '        If dr.Cells("mathang_id").Value IsNot DBNull.Value Then
    '            If CInt(dr.Cells("mathang_id").Value) = mathang_id Then
    '                Return False
    '            End If
    '        End If
    '    Next
    '    Return True
    'End Function

    Public Sub AddMatHang(ByVal objMatHang As CMatHang, ByVal slkh As Double, ByVal count As Integer)
        'If isNewMatHang(objMatHang.MatHang_ID) Then
        'end If
        Dim dt As DataTable = dsDataSet.Tables(0)
        Dim NewRow As DataRow
        NewRow = dt.NewRow
        NewRow("makho") = objMatHang.Kho
        NewRow("kho") = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.KHO, objMatHang.Kho).Ten
        NewRow("mathang_id") = objMatHang.MatHang_ID
        NewRow("ma") = objMatHang.Ma
        NewRow("code") = objMatHang.Code
        NewRow("ten") = objMatHang.Ten
        NewRow("dvt") = objMatHang.DVT
        NewRow("lo") = objMatHang.Lo
        NewRow("hansd") = objMatHang.HanSD
        NewRow("lk") = objMatHang.LK
        NewRow("h") = objMatHang.H
        NewRow("slnx_id") = DBNull.Value
        '***Phai doi ra dung format truoc khi tinh thanh tien
        If slkh > 0 Then
            slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
        End If
        NewRow("slkh") = slkh
        NewRow("slth") = 0
        NewRow("gle") = objMatHang.Gle
        'Tinh thanh tien sau khi format xong
        Dim thanhtien As Double = slkh * objMatHang.Gle
        NewRow("thanhtien") = CType(thanhtien, Long)
        NewRow("ghichu") = ""
        Try
            NewRow("dpnx_id") = objPhieu.DPNX_ID
        Catch ex As Exception
            NewRow("dpnx_id") = DBNull.Value
        End Try
        NewRow("sltonkh") = objMatHang.SLTonKH
        NewRow("sltonth") = objMatHang.SLTonTH
        NewRow("sltonss") = objMatHang.SLTonSS
        If count = 1 Then
            'Lay cell dang chon de xac dinh RowIndex cua dong can them
            'Sau do them mat hang moi vao
            Dim RowIndex As Integer = gridCTPhieu.SelectedCells(0).RowIndex
            gridCTPhieu.Rows.RemoveAt(RowIndex) 'Xoa cai dong tai vi tri can insert
            dt.AcceptChanges()
            dt.Rows.InsertAt(NewRow, RowIndex) 'Add vao vi tri insert
            dt.AcceptChanges()
            gridCTPhieu.Rows(RowIndex).HeaderCell.Value = (RowIndex + 1).ToString 'Hien thi lai STT o dau moi dong
            gridCTPhieu.Refresh() 'Refresh lai
        Else
            dt.Rows.InsertAt(NewRow, dt.Rows.Count)
            dt.AcceptChanges()
            gridCTPhieu.Rows(dt.Rows.Count - 1).HeaderCell.Value = (dt.Rows.Count).ToString
            gridCTPhieu.Refresh()
        End If
        ShowSoKH_TGiaTri()
    End Sub

    'Bien Count cho biet nguoi dung se add nhieu mat hang vao cung mot luc hay ko?
    'Neu count = 1 thi add mot mat hang duy nhat
    'neu count > 1 thi add nhieu mat hang mot luc
    Public Sub AddNhomHang(ByVal mathuoc As String, ByVal count As Integer)
        Dim objThuoc As CThuoc = CThuocs.GetThuocByMa(mathuoc)
        dsDataSet.GetChanges()
        Dim dt As DataTable = dsDataSet.Tables(0)
        Dim NewRow As DataRow
        NewRow = dt.NewRow
        NewRow("ma") = objThuoc.MaThuoc
        NewRow("code") = CThuocs.GetNewCode(objThuoc.MaThuoc)
        NewRow("ten") = objThuoc.TenThuoc
        NewRow("dvt") = objThuoc.DonViTinh
        NewRow("lk") = cmbLK.SelectedValue
        NewRow("h") = 1
        Try
            NewRow("dpnx_id") = objPhieu.DPNX_ID
        Catch ex As Exception
            NewRow("dpnx_id") = DBNull.Value
        End Try
        If count = 1 Then
            'Lay cell dang chon de xac dinh RowIndex cua dong can them
            'Sau do them mat hang moi vao
            Dim RowIndex As Integer = gridCTPhieu.SelectedCells(0).RowIndex
            NewRow("makho") = gridCTPhieu.Rows(RowIndex).Cells("makho").Value
            gridCTPhieu.Rows.RemoveAt(RowIndex)
            dt.AcceptChanges()
            dt.Rows.InsertAt(NewRow, RowIndex)
            dt.AcceptChanges()
            gridCTPhieu.Rows(RowIndex).HeaderCell.Value = (RowIndex + 1).ToString
            gridCTPhieu.Refresh()
        Else 'Neu count > 1 thi tiep tuc add mat hang moi vao - Xu ly bang cach add them row trong datagrid
            NewRow("makho") = dt.Rows(dt.Rows.Count - 1).Item("makho")
            dt.Rows.InsertAt(NewRow, dt.Rows.Count)
            dt.AcceptChanges()
            gridCTPhieu.Rows(dt.Rows.Count - 1).HeaderCell.Value = (dt.Rows.Count).ToString
            gridCTPhieu.Refresh()
        End If
        ShowSoKH_TGiaTri()
    End Sub

    'Ham nay dung de hien thi tong gia tri phieu va so khoan cua phieu
    Public Sub ShowSoKH_TGiaTri()
        Dim sum As Double = 0
        RowCount = GetRowCount()
        For i As Integer = 0 To RowCount - 1
            gridCTPhieu.Rows(i).HeaderCell.Value = (i + 1).ToString
            If gridCTPhieu.Rows(i).Cells("thanhtien").Value IsNot DBNull.Value Then
                sum += gridCTPhieu.Rows(i).Cells("thanhtien").Value
            End If
        Next
        txtSoKH.Text = CStr(RowCount)
        txtTGiaTri.Text = Format(sum, FormatMoneyStyle())
    End Sub

    'Ham nay dung de thay the MaKho textbox column thanh combobox column
    Private Sub AddComboBoxColumns_Kho()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        With comboboxColumn
            .Name = "makho"
            .Frozen = True
            .DataPropertyName = "makho"
            .HeaderText = "Kho"
            .FlatStyle = FlatStyle.Flat
            .DropDownWidth = 150
            .Width = gridCTPhieu.Columns("makho").Width
            .DataSource = CDoiTuongs.GetDoiTuongList(enumDOITUONG.KHO)
            .ValueMember = "KH"
            .DisplayMember = "Ten"
            .DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
        End With
        Try
            gridCTPhieu.Columns.Remove("makho")
            gridCTPhieu.Columns.Insert(0, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de thay the textbox column thanh combobox column
    Private Sub AddComboBoxColumns_CCL()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        With comboboxColumn
            .Name = "h"
            .DataPropertyName = "h"
            .HeaderText = "CCL"
            .DropDownWidth = 30
            .Width = 30
            .FlatStyle = FlatStyle.Flat
            .DataSource = CDoiTuongs.GetDoiTuongList(enumDOITUONG.CCL)
            .ValueMember = "KH"
            .DisplayMember = "Ten"
            .DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
        End With
        Try
            Dim index As Integer = gridCTPhieu.Columns("h").Index
            gridCTPhieu.Columns.Remove("h")
            gridCTPhieu.Columns.Insert(index, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de thay the text column thanh DateTimePicker Column
    Private Sub AddDateTimePickerColumns_HSD()
        Dim datetimeColumn As New CalendarColumn()
        With datetimeColumn
            .Name = "hansd"
            .DataPropertyName = "hansd"
            .HeaderText = "Hạn SD"
        End With
        Try
            Dim index As Integer = gridCTPhieu.Columns("hansd").Index
            gridCTPhieu.Columns.Remove("hansd")
            gridCTPhieu.Columns.Insert(index, datetimeColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de dem so row co trong grid
    Public Function GetRowCount() As UInteger
        Dim mRowCount As UInteger = 0
        Try
            If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                mRowCount = gridCTPhieu.RowCount - 1
            ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                mRowCount = gridCTPhieu.RowCount
            End If
        Catch ex As Exception
            mRowCount = 0
        End Try
        Return mRowCount
    End Function

    'Ham nay dung de luu row trong grid thanh doi tuong CMatHang
    Private Function GetMatHang(ByVal dr As DataGridViewRow, ByRef obj As CMatHang) As Boolean
        Dim len As Integer = 0
        obj = New CMatHang
        With obj
            Try
                .Ma = dr.Cells("ma").Value
            Catch ex As Exception
                ShowError("Mã mặt hàng chưa chọn")
                dr.Cells("ten").Selected = True
                Return False
            End Try

            .Kho = dr.Cells("makho").Value
            If .Kho.Trim() = "" Or .Kho.Trim() = "0001" Then
                ShowError("Kho cụ thể chưa chọn")
                dr.Cells("makho").Selected = True
                Return False
            End If
            

            .Ten = dr.Cells("ten").Value
            'Kiểm tra độ dài hợp lệ
            len = .ColumnLength("ten")
            If len < .Ten.Length Then
                ShowMessages("Chiều dài ký tự Tên mặt hàng vượt quá " + len.ToString())
                dr.Cells("ten").Selected = True
                Return False
            End If

            .Code = dr.Cells("code").Value

            Try
                .Lo = dr.Cells("lo").Value
                If .Lo.Trim() = "" Then
                    .Lo = Nothing
                End If
            Catch ex As Exception
                .Lo = Nothing
            End Try
            'Kiểm tra độ dài hợp lệ
            If .Lo IsNot Nothing Then
                len = .ColumnLength("lo")
                If len < .Lo.Length Then
                    ShowMessages("Chiều dài ký tự Lô hàng vượt quá " + len.ToString())
                    dr.Cells("lo").Selected = True
                    Return False
                End If
            End If

            Try
                .HanSD = dr.Cells("hansd").Value
                If .HanSD.Trim() = "" Then
                    .HanSD = Nothing
                End If
            Catch ex As Exception
                .HanSD = Nothing
            End Try
            'Kiểm tra độ dài hợp lệ
            If .HanSD IsNot Nothing Then
                len = .ColumnLength("hansd")
                If len < .HanSD.Length Then
                    ShowMessages("Chiều dài ký tự Hạn sử dụng vượt quá " + len.ToString())
                    dr.Cells("hansd").Selected = True
                    Return False
                End If
            End If

            Dim objLK As CDoiTuong = cmbLK.SelectedItem
            .LK = objLK.KH

            Try
                .H = dr.Cells("h").Value
            Catch ex As Exception
                .H = Nothing
            End Try

            Try
                obj.NgTTon = dr.Cells("ngtton").Value
            Catch ex As Exception
                obj.NgTTon = dtNgay.Value.Date
            End Try

            If g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANKEHOACH) Then
                Try
                    .SLTonKH = dr.Cells("slkh").Value
                    dr.Cells("slth").Value = 0
                    If .SLTonKH = 0 Then
                        ShowError("SLKH chưa nhập.")
                        dr.Cells("slkh").Selected = True
                        Return False
                    ElseIf .SLTonKH < 0 Then
                        ShowError("SLKH phải > 0.")
                        dr.Cells("slkh").Selected = True
                        Return False
                    End If
                Catch ex As Exception
                    ShowError("SLKH chưa nhập.")
                    dr.Cells("slkh").Selected = True
                    Return False
                End Try
            ElseIf g_User.Ban_ID = LocPhanQuyen(enumPHANQUYEN.BANTAICHINH) Then
                'Neu tai chinh xac nhan
                If chkTCXacNhan.Checked = True Then
                    .SLTonTH = dr.Cells("slth").Value
                    If .SLTonTH = 0 Then
                        ShowError("SLTH chưa nhập.")
                        dr.Cells("slth").Selected = True
                        Return False
                    ElseIf .SLTonTH < 0 Then
                        ShowError("SLTH phải > 0.")
                        dr.Cells("slth").Selected = True
                        Return False
                    End If
                End If
            End If
            .DVT = dr.Cells("dvt").Value
            .Gle = ChuanHoaSo(dr.Cells("gle").Value)
        End With
        Return True
    End Function

    Public Function CompareValue(ByVal value1 As Object, ByVal value2 As Object) As Boolean
        If value1 Is DBNull.Value And value2 Is DBNull.Value Then
            Return True
        ElseIf value1 IsNot DBNull.Value And value2 IsNot DBNull.Value Then
            If value1 = value2 Then
                Return True
            Else
                Return False
            End If
        End If
        Return False
    End Function

    Public Function KiemTraMatHangGiongNhau() As Boolean
        Dim dvrI, dvrJ As DataGridViewRow
        For i As Integer = 0 To RowCount - 2
            dvrI = gridCTPhieu.Rows(i)
            For j As Integer = i + 1 To RowCount - 1
                dvrJ = gridCTPhieu.Rows(j)
                If CompareValue(dvrI.Cells("kho").Value, dvrJ.Cells("kho").Value) And _
                    CompareValue(dvrI.Cells("ma").Value, dvrJ.Cells("ma").Value) And _
                    CompareValue(dvrI.Cells("ten").Value, dvrJ.Cells("ten").Value) And _
                    CompareValue(dvrI.Cells("lo").Value, dvrJ.Cells("lo").Value) And _
                    CompareValue(dvrI.Cells("hansd").Value, dvrJ.Cells("hansd").Value) And _
                    CompareValue(dvrI.Cells("dvt").Value, dvrJ.Cells("dvt").Value) And _
                    CompareValue(dvrI.Cells("h").Value, dvrJ.Cells("h").Value) And _
                    CompareValue(dvrI.Cells("lk").Value, dvrJ.Cells("lk").Value) And _
                    CompareValue(dvrI.Cells("gle").Value, dvrJ.Cells("gle").Value) Then
                    Dim str As String = String.Format("Mặt hàng thứ {0} trùng với mặt thứ {1}", i + 1, j + 1)
                    ShowError(str)
                    Return True
                End If
            Next
        Next
        Return False
    End Function

    Public Function InsertDPNX() As Boolean
        Dim objMH(RowCount - 1) As CMatHang
        Dim dvr As DataGridViewRow
        objPhieu = New CPhieuNX()
        'Kiem tra va Luu thong tin DPNX
        If PopulatePhieuInfo() Then
            'Kiem tra xem co ton tai 2 mat hang them vao giong nhau ko
            If KiemTraMatHangGiongNhau() Then
                objPhieu = Nothing 'Reset lai objPhieu
                Return False
            End If
            'Kiem tra va luu thong tin SLNX
            For i As Integer = 0 To RowCount - 1
                dvr = gridCTPhieu.Rows(i)
                If Not GetMatHang(dvr, objMH(i)) Then
                    objPhieu = Nothing 'Reset lai objPhieu
                    Return False
                End If
            Next
            'Kiem tra xem sluong luc bat dau ghi co > slton nua ko (truong hop dung nhieu may khi xuat phieu)
            If enumNX = enumDOITUONG.TINHCHATXUAT Then
                Dim objMHang As CMatHang
                Dim dr As DataGridViewRow
                Dim strErr As String
                For i As Integer = 0 To RowCount - 1
                    dr = gridCTPhieu.Rows(i)
                    objMHang = CMatHangs.GetMatHangByMa(dr.Cells("mathang_id").Value)
                    CMatHangs.GetSLTonDenNgay(-1, objMHang.MatHang_ID, dtNgay.Value.Date, sltonkh, Nothing, Nothing, Nothing)
                    If dr.Cells("slkh").Value > sltonkh Then
                        strErr = "Số lượng kế hoạch của mặt hàng " + dr.Cells("ten").Value.ToString() + " lớn hơn số lượng tồn kế hoạch"
                        ShowMessages(strErr)
                        dr.Selected = True
                        Return False
                    End If
                Next
            End If

            'Kiem tra va Them phieu nhap xuat neu dc
            If objPhieu.Insert() > 0 Then
                For Each dr As DataRow In dsDataSet.Tables(0).Rows
                    dr("dpnx_id") = objPhieu.DPNX_ID
                Next
                If enumNX = enumDOITUONG.TINHCHATNHAP Then
                    'Them cac mat hang moi vao
                    For i As Integer = 0 To RowCount - 1
                        'Kiem tra mat hang nay da ton tai chua
                        If objMH(i).IsExists() < 0 Then
                            objMH(i).Insert()
                            If objMH(i).MatHang_ID = 0 Then
                                ShowMessages("tblTon chưa thiết lập autonumber mã mặt hàng.")
                                objPhieu.Delete()
                                Exit Function
                            End If
                        Else
                            objMH(i).UpdateNgayTaoTon(dtNgay.Value.Date)
                            objMH(i).AddSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                        End If
                        'Du mat hang la them moi hay da co roi thi van lay lai mathang_id va code de cap nhat
                        gridCTPhieu.Rows(i).Cells("mathang_id").Value = objMH(i).MatHang_ID
                        gridCTPhieu.Rows(i).Cells("code").Value = objMH(i).Code
                    Next
                ElseIf enumNX = enumDOITUONG.TINHCHATXUAT Then
                    For i As Integer = 0 To RowCount - 1
                        objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                        objMH(i).SubstractSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                    Next
                End If
                    
                End If
                Dim objSLNX As CSLNX
                For i As Integer = 0 To RowCount - 1
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieu.DPNX_ID
                    objSLNX.MATHANG_ID = dr.Cells("mathang_id").Value
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    'Insert SLNX
                    dr.Cells("slnx_id").Value = objSLNX.Insert()
                Next
                ShowSoKH_TGiaTri()
                objPhieu.SOKH = txtSoKH.Text
                objPhieu.TGIATRI = txtTGiaTri.Text
                objPhieu.Update()
                ShowMessages("Đã thêm phiếu mới xong.")
                Return True
            End If
        Return False
    End Function

    Public Function UpdateDPNX() As Boolean
        Dim objMH(RowCount - 1) As CMatHang
        Dim dvr As DataGridViewRow
        If PopulatePhieuInfo() Then
            'Kiem tra xem co ton tai 2 mat hang them vao giong nhau ko
            If KiemTraMatHangGiongNhau() Then
                Return False
            End If
            'Kiem tra va luu thong tin SLNX
            For i As Integer = 0 To RowCount - 1
                dvr = gridCTPhieu.Rows(i)
                If Not GetMatHang(dvr, objMH(i)) Then
                    Return False
                End If
            Next

            'Kiem tra lai xem so luong luc bat dau ghi co > slton nua ko (truong hop dung nhieu may khi xuat phieu)
            If enumNX = enumDOITUONG.TINHCHATXUAT Then
                Dim objMHang As CMatHang
                Dim dr As DataGridViewRow
                Dim strErr As String
                For i As Integer = 0 To RowCount - 1
                    dr = gridCTPhieu.Rows(i)
                    objMHang = CMatHangs.GetMatHangByMa(dr.Cells("mathang_id").Value)
                    CMatHangs.GetSLTonDenNgay(objPhieu.DPNX_ID, objMHang.MatHang_ID, dtNgay.Value.Date, sltonkh, Nothing, Nothing, Nothing)
                    If dr.Cells("slkh").Value > sltonkh Then
                        strErr = "Số lượng kế hoạch của mặt hàng " + dr.Cells("ten").Value.ToString() + " lớn hơn số lượng tồn kế hoạch"
                        ShowError(strErr)
                        dr.Selected = True
                        Return False
                    End If
                Next
            End If

            'Kiem tra va Cap nhat phieu nhap xuat neu dc
            If objPhieu.Update() > 0 Then
                'Update lai slton cua cac mathang <=> xoa het du lieu trong bang SLNX
                CMatHangs.UpdateSLTONMatHangByDPNX(objPhieu.DPNX_ID)
                'Xoa het cac SLNX trong tblSLNX theo DPNX_ID
                CSLNXs.DeleteSLNXByDPNX_ID(objPhieu.DPNX_ID)

                'Xet truong hop la phieu nhap neu co mat hang moi them vao
                If enumNX = enumDOITUONG.TINHCHATNHAP Then
                    'Them cac mat hang moi vao
                    For i As Integer = 0 To RowCount - 1
                        If objMH(i).IsExists() < 0 Then
                            objMH(i).Insert()
                            If objMH(i).MatHang_ID = 0 Then
                                ShowMessages("tblTon chưa thiết lập autonumber mã mặt hàng.")
                                ShowSoKH_TGiaTri()
                                objPhieu.SOKH = txtSoKH.Text
                                objPhieu.TGIATRI = txtTGiaTri.Text
                                objPhieu.Update()
                                Exit Function
                            End If
                        Else
                            objMH(i).UpdateNgayTaoTon(dtNgay.Value.Date)
                            objMH(i).AddSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                        End If
                        gridCTPhieu.Rows(i).Cells("mathang_id").Value = objMH(i).MatHang_ID
                        gridCTPhieu.Rows(i).Cells("code").Value = objMH(i).Code
                    Next
                ElseIf enumNX = enumDOITUONG.TINHCHATXUAT Then
                    For i As Integer = 0 To RowCount - 1
                        objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                        objMH(i).SubstractSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                    Next
                End If
                'Them lai cac SLNX vao tblSLNX
                Dim objSLNX As CSLNX
                For i As Integer = 0 To RowCount - 1
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieu.DPNX_ID
                    objSLNX.MATHANG_ID = dr.Cells("mathang_id").Value
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    dr.Cells("slnx_id").Value = objSLNX.Insert()
                Next
                ShowSoKH_TGiaTri()
                objPhieu.SOKH = txtSoKH.Text
                objPhieu.TGIATRI = txtTGiaTri.Text
                objPhieu.Update()
                ShowMessages("Đã cập nhật xong")
                Return True
            End If
        End If
        Return False
    End Function

    Public Function CheckTCXacNhan() As Boolean
        'Hien thi chkTCXacNhan.Checked = true neu tat ca slth > 0
        'Nguoc lai chkTCXacNhan.Checked = false neu ton tai slth <= 0
        Dim isCheckTCXacNhan As Boolean = True
        For Each dr As DataGridViewRow In gridCTPhieu.Rows
            If dr.Cells("slth").Value IsNot DBNull.Value Then
                If dr.Cells("slth").Value <= 0 Then
                    isCheckTCXacNhan = False
                End If
            Else
                isCheckTCXacNhan = False
            End If
        Next
        If isCheckTCXacNhan Then
            lblBCTH.Text = "Đã xác nhận (TC)"
        Else
            lblBCTH.Text = "Chưa xác nhận (KH)"
        End If
        Return isCheckTCXacNhan
    End Function
#End Region

    Private Sub gridCTPhieu_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles gridCTPhieu.CellValidating
        ' Validate the CompanyName entry by disallowing empty strings.
        If gridCTPhieu.Columns(e.ColumnIndex).Name = "SLKH" Then
            If e.FormattedValue < 0 Then
                gridCTPhieu.Rows(e.RowIndex).ErrorText = "Số lượng kế hoạch phải > 0"
                ShowMessages("Số lượng kế hoạch phải > 0")
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub gridCTPhieu_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellContentClick

    End Sub
End Class